package cn.com.taiji.oospub.wechat.controller;


import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.entity.MemberBaseInfo;
import cn.com.taiji.oospub.wechat.entity.SystemLogMember;
import cn.com.taiji.oospub.wechat.service.ISystemLogMemberService;
import cn.com.taiji.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;

import static cn.com.taiji.oospub.wechat.controller.BaseLogController.toLogString;


/**
 *
 * @author Peream <br>
 *         Create Time：2011-5-20 下午03:06:58<br>
 *         <a href="mailto:peream@gmail.com">peream@gmail.com</a>
 * @since 1.0
 * @version 1.0
 */
public abstract class WXBaseLogController extends BaseController
{
	@Autowired
	protected ISystemLogMemberService logManager;

	protected void addLoginLog(HttpServletRequest request, String info, Object... args)
	{
		addLog(request, SystemLogMember.LogType.LOGIN, info, args);
	}

	protected void addSysLog(HttpServletRequest request, String info, Object... args)
	{
		addLog(request, SystemLogMember.LogType.SYSTEM, info, args);
	}

	protected void addLog(HttpServletRequest request, SystemLogMember.LogType type, String info, Object... args)
	{
		MemberBaseInfo entity = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
		String ip = (String) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_IP);
		SystemLogMember log = new SystemLogMember();
		log.setMemberId(entity.getId());
		log.setIp(ip);
		log.setOptime(LocalDateTime.now());
		log.setLogType(type);
		log.setInfo(toLogString(info, args));
		logManager.save(log);
	}

   protected void writeSuccessToBrowers(String message,HttpServletResponse response) throws IOException {
        String text = "{\"result\":\"success\",\"message\":\"" + message + "\"}";
        response.setHeader("ContentType", "text/json");
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println(text);
        response.getWriter().close();
    }

   protected void writeFailToBrowers(String message,HttpServletResponse response) throws IOException {
       String text = "{\"result\":\"fail\",\"message\":\"" + message + "\"}";
       response.setHeader("ContentType", "text/json");
       response.setHeader("Content-Type", "text/html;charset=UTF-8");
       response.setCharacterEncoding("UTF-8");
       response.getWriter().println(text);
       response.getWriter().close();
   }

   public String strcat( String...args)
   {
       StringBuilder result = new StringBuilder( "");
       for( String arg : args){
           result.append( arg);
       }
       return result.toString();
   }

   /**
    * 下载附件使用
    * @Title: doDownLoad
    * @return void 返回类型
    * @throws
    */
   protected void doDownLoad(final HttpServletRequest request, final HttpServletResponse response,final InputStream stream, String displayName) throws IOException
   {
       Assert.notNull(stream, "被下载的文件流不能为空");
       Assert.hasText(displayName, "显示名称必须指定");
       String ua = request.getHeader("user-agent"); // 获取终端类型
       if (ua == null) {
           ua = " User-Agent: Mozilla/4.0 (compatible; MSIE 6.0;) ";
       }
       boolean isIE = ua.toLowerCase().indexOf(" msie ") != -1;

       response.setCharacterEncoding("utf-8");
       response.setHeader("Cache-Control", "no-cache");
       response.setContentType("application/octet-stream;charset=ISO8859-1");
       if (isIE) {
           response.setContentType("application/x-download");// 设置为下载application/x-download
       }
       // 解决中文乱码
     response.setHeader("Content-Disposition", "attachment;filename=" + new String(displayName.getBytes("GBK"), "iso8859-1"));

       OutputStream output = null;
       InputStream fis = null;
       try
       {
           // 设置长度
           response.setContentLength(stream.available());
           output = response.getOutputStream();
           fis = stream;
           byte[] b = new byte[1024];
           int i = 0;
           while ((i = fis.read(b)) > 0)
           {
               output.write(b, 0, i);
           }
           output.flush();
       }
       catch (Exception e)
       {
           logger.error(e.getMessage(), e);
       }
       finally
       {
           if (fis != null)
           {
               fis.close();
               fis = null;
           }
           if (output != null)
           {
               output.close();
               output = null;
           }
       }
   }
	protected void setExcelHeader(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename="+
				new String(fileName.getBytes(GBK), ISO8859));
	}
}

